package gms;

import java.util.Date;
import java.util.ArrayList;

/**
 * This class is responsible for checking the views, and
 * making sure that processes are working correctly. 
 * We add a threshold value in seconds and make sure that
 * the timestamps in the views don't exceed this value. 
 * 
 */

public class ViewValidationService implements Runnable
{

	/**
	 * Can set this to true if we wish to terminate the process 
	 * gracefully
	 */
	private boolean mTerminated = false; 
	
	/**
	 * The threshold to wait for; if larger, then that
	 * means failure 
	 */
	private char mThresholdSeconds = 5; 
	
	/**
	 * The data structure we want to check over time
	 */
	private ArrayList<View> mViews; 
	
	/**
	 * Default constructor, receives reference to array
	 * to check periodically.
	 * @param iViewArr
	 */
	public ViewValidationService(ArrayList<View> iViewArr)
	{
		mViews = iViewArr;
	}
	
	/**
	 * Main checking routine. 
	 */
	@Override
  public void run()
  {
		int i; 
		
		System.out.println("View Validation service started");
		
	  while(!mTerminated)
	  { 
	  	synchronized(mViews)
			{
		  	for (i=0; i<mViews.size(); ++i)
		  	{
	
		  		/* This means we have assumed it has died, hence
		  		 * remove from the current view  */
		  		if (mViews.get(i).getDifference() > mThresholdSeconds)
		  		{
		  				System.out.println("Remove : " + mViews.get(i).toString());
		  				mViews.remove(i);
		  		}
		  	}
		  } // end for
	  	
	  	try
      {
	      Thread.sleep(500);
      } 
	  	catch (InterruptedException e)
      {
	      e.printStackTrace();
      }
	  	
	  } // end while
  }
	
	/**
	 * Terminate the process
	 */
	public void terminate()
	{
		mTerminated = true; 
	}

}
